package com.jeff.android.lab.algorithm;

import android.widget.TextView;

import com.jeff.android.lab.BaseFragment;
import com.jeff.android.lab.R;

import butterknife.BindView;
import butterknife.OnClick;

/*
* 冒泡排序(Bubble Sort)
* 时间复杂度 O（n²）
* */
public class BubbleSortFragment extends BaseFragment {

    @BindView(R.id.tv_source)
    TextView tv_source;

    @BindView(R.id.tv_result)
    TextView tv_result;

    private int[] data = {49, 38, 65, 97, 76, 13, 27};

    @Override
    protected int getRootLayout() {
        return R.layout.algorithm_fragment_quick_sort;
    }

    @Override
    protected void initView() {
        super.initView();
        print(tv_source);
    }

    @Override
    protected void initData() {
        sort(data);
        print(tv_result);
    }

    /*
    *
    * */
    private void sort(int arr[]) {
        int length = arr.length;
        int k = 0; // 每轮比较后，需要比较的长度递减1
        for (int i = 0; i < length - 1; i++) {
            for (int j = 0; j < length - i - 1; j++) {
                if (arr[j]  > arr[j+1]) {
                    int tmp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = tmp;
                }
            }
        }
    }


    private void print(TextView tv) {
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < data.length; i++) {
            sb.append(data[i]);
            if (i < data.length - 1)
                sb.append(",");
        }
        tv.setText(sb.toString());
    }

}
